package com.hwbsite.hwbback.config;

import cn.hutool.jwt.JWTUtil;
import com.hwbsite.hwbback.consstants.CommonConstants;
import com.hwbsite.hwbback.entity.HwbUser;
import com.hwbsite.hwbback.service.CommonService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class MyAuthFilter extends OncePerRequestFilter {

    @Autowired
    private CommonService commonService;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        if (token != null) {
            if(!JWTUtil.verify(token, CommonConstants.JWT_KEY.getBytes())){
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效令牌");
                return;
            }

            // 2. Redis黑名单检查
            if (!commonService.isTokenValid(token)) {
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效令牌");
                return;
            }

            String username = (String) JWTUtil.parseToken(token).getPayload("username");

            UserDetails hwbUser =  userDetailsService.loadUserByUsername(username);

            // 3. 构建认证对象
            Authentication auth =    new UsernamePasswordAuthenticationToken(hwbUser, null, hwbUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
